'use strict'

import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import { judgeTokenAccess } from '../axios/utils'

// Full config:  https://github.com/axios/axios#request-config
axios.defaults.baseURL = process.env.VUE_APP_BASE_API
// axios.defaults.headers.common['Authorization'] = ''
axios.defaults.headers.common['Accept'] = 'application/vnd.gvrbox.v1+json' // 添加通用头部参数Accept,固定值:application/vnd.gvrbox.v1+json
// axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded'

let config = {
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data
    if (!headers['Content-Type']) return qs.stringify(data)
    switch (headers['Content-Type'].toLowerCase()) {
      case 'application/json;chartset=urf-8': {
        return JSON.stringify(data)
      }
      case 'multipart/form-data;charset=urf-8': {
        return data
      }
      default: {
        return qs.stringify(data)
      }
    }
  }]
}

const _axios = axios.create(config)
_axios.interceptors.request.use(
  async function (config) {
    // Do something before request is sent
    let token = await judgeTokenAccess()
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    if (response.data.status_code === 200) {
      return {
        err: null,
        data: response.data.data
      }
    } else {
      return {
        err: response.data,
        data: null
      }
    }
  },
  function (error) {
    // Do something with response error
    return {
      err: error.response.data,
      data: null
    }
  }
)

Plugin.install = function (Vue, options) {
  Vue.axios = _axios
  window.axios = _axios
  Object.defineProperties(Vue.prototype, {
    axios: {
      get () {
        return _axios
      }
    },
    $axios: {
      get () {
        return _axios
      }
    }
  })
}

Vue.use(Plugin)

export default _axios
